package com.mycontract.suitepro.network

import com.mycontract.suitepro.data.*
import com.mycontract.suitepro.extend.toContractSuiteFullContractSuiteUrlContractSuitePath
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.RuntimeException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

object ApiUserNetwork {

    private val garlic_loanServiceApi = ApiServiceCreator.create<ApiUserService>()

    suspend fun getContractOrderList(reqGetContractList: ReqGetContractList) =
        garlic_loanServiceApi.getContractOrderList(
            ApiUrl.CONTRACTSUITE_PATH_GET_CONTRACT_ORDER_LIST.toContractSuiteFullContractSuiteUrlContractSuitePath(),
            reqGetContractList
        ).await()

    suspend fun signContract(reqSignContract: ReqSignContract) =
        garlic_loanServiceApi.signContract(
            ApiUrl.CONTRACTSUITE_PATH_SIGN_CONTRACT.toContractSuiteFullContractSuiteUrlContractSuitePath(),
            reqSignContract
        ).await()

    suspend fun getAppConfig(reqBase: ReqBase) =
        garlic_loanServiceApi.getAppConfig(
            ApiUrl.CONTRACTSUITE_PATH_APP_CONFIG.toContractSuiteFullContractSuiteUrlContractSuitePath(),
            reqBase
        ).await()

    private suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) continuation.resume(body)
                    else continuation.resumeWithException(
                        RuntimeException("response body is null")
                    )
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }
            })
        }
    }
}